<template>
  <!-- 添加脸谱 -->
  <view id="container">
    <image src="https://z3.ax1x.com/2021/09/02/hD6GsU.png" class="banner"></image>
    <view class="information">
      <view class="title">
        <view class="vertical-bar"></view>
        <view class="txt">一、填写基本信息</view>
      </view>
      <!-- 1.0 基本信息表单 -->
      <u-form :model="form" ref="uForm" class="content">
        <!-- 姓名 -->
        <u-form-item :required="true" label="姓名" class="content-item">
          <view class="content-input">
            <u-input v-model="form.name" placeholder="请输入姓名" />
          </view>
        </u-form-item>

        <!-- 家庭关系 -->
        <u-form-item :required="true" label="家庭关系" label-width="150" class="content-item">
          <view style="display: flex; flex-direction: row; justify-content: flex-start; align-items: flex-start; width: 100%; flex-wrap: wrap">
            <view
              style="width: 100rpx; height: 42rpx; line-height: 42rpx; margin: 5rpx 5rpx; border-radius: 7rpx; font-size: 20rpx; text-align: center; position: relative; background-color: #e8e8e8"
              v-for="(item, index) in ralationList"
              @click="relationChange(item.name, index)"
              :class="item.checked ? 'active' : ''"
            >
              {{ item.name }}
              <icon type="success" size="10" color="#FF7E00" style="position: absolute; top: -15rpx; right: -5rpx" v-if="item.checked" />
            </view>
          </view>
        </u-form-item>

        <!-- 性别 -->
        <u-form-item label="性别" :required="true" prop="sex" class="content-item">
          <view class="choose">
            <radio-group>
              <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in sex_box" @click="sex_change(index)">
                <view>
                  <radio :checked="item.checked" />
                </view>
                <view>{{ item.name }}</view>
              </label>
            </radio-group>
          </view>
        </u-form-item>

        <!-- 年龄 -->
        <u-form-item :required="true" label="年龄" class="content-item">
          <view class="content-input">
            <u-input v-model="form.age" placeholder="请填写大致年龄" type="number" />
            <view style="padding-right: 10rpx">岁</view>
          </view>
        </u-form-item>

        <!-- 身高 -->
        <u-form-item :required="true" label="身高" class="content-item">
          <view class="content-input">
            <u-input v-model="form.height" placeholder="请填写大致身高" type="number" />
            <view style="padding-right: 10rpx">cm</view>
          </view>
        </u-form-item>
      </u-form>
    </view>

    <!-- 2.0 拍摄人脸 -->
    <view class="information" style="margin-top: 14rpx; padding-bottom: 63rpx">
      <view class="title">
        <view class="vertical-bar"></view>
        <view class="txt" style="margin-bottom: 10rpx">拍摄人脸</view>
      </view>
      <view class="img-content" style="">
        <view v-if="local_img.length != 0" style="display: flex; flex-direction: row; justify-content: flex-start; align-items: center; flex-wrap: wrap; padding: 40rpx 0rpx">
          <view style="position: relative" v-for="(item2, index) in local_img">
            <image :src="item2" mode="aspectFill" style="width: 26vw; height: 26vw; border-radius: 10rpx; margin-right: 10rpx" v-if="index != local_img.length - 1"></image>
            <image
              src="../../static/facebook/sc_2.png"
              style="top: 5rpx; right: 5rpx; position: absolute; width: 28rpx; height: 28rpx"
              v-if="index != local_img.length - 1"
              @click="user_delete_pic(index)"
            ></image>
            <image
              src="../../static/facebook/xztp.png"
              style="width: 25vw; height: 25vw; border-radius: 10rpx"
              @click="chooseImg"
              v-if="index == local_img.length - 1"
              v-show="local_img.length < 7"
            ></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 3.0 电话绑定 -->
    <view class="information" style="margin-top: 14rpx">
      <view class="title">
        <view class="vertical-bar"></view>
        <view class="txt">
          将人脸与你的电话绑定
          <text class="tips">（最多可绑定3个）</text>
        </view>
      </view>
      <view class="phone-tips">走失后，扫描人脸即可拨通你的电话</view>

      <u-checkbox-group :wrap="true" style="margin-left: 70rpx">
        <u-checkbox v-model="item.checked" v-for="(item, index) in phone_list" style="margin: 10rpx 0">
          {{ item.mobile }}
        </u-checkbox>
      </u-checkbox-group>

      <view class="phone-add-btn" style="color: #cccccc; margin-left: 70rpx" @click="goto_addmore_phonenumber">
        <u-icon class="plus" name="plus" size="48" color="#CCCCCC" style="margin-bottom: 50rpx; margin-top: 50rpx"></u-icon>
        添加号码
      </view>
    </view>
    <!-- 用户协议 -->
    <view class="information protocal">
      <u-checkbox-group>
        <u-checkbox v-model="item.checked" v-for="(item, index) in agree_list" style="margin: 10rpx 0">
          <text>{{ item.txt1 }}</text>
          <text style="color: #ff804c" @click.stop="see_face_protocal">{{ item.txt2 }}</text>
        </u-checkbox>
      </u-checkbox-group>
    </view>
    <view class="issue-btn" @click="generateFacebook">生成脸谱</view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import { getImageData, getFloatLocationByExif } from '../../js_sdk/iz-exif/js_sdk/izExif/izExif.js'
var img_tool = require('image-tools')

export default {
  data() {
    return {
      human_id: '',
      local_img: ['../../static/facebook/xztp.png'],
      net_img: [],
      header_info: {},
      form_info: {},
      action_url: '#',
      err_toast: false,
      phone_list: [],
			formPhone: [],
      sex_box: [
        {
          value: 1,
          name: '男',
          checked: false
        },
        {
          value: 2,
          name: '女',
          checked: false
        }
      ],
      form: {
        name: '',
        relation: '',
        sex: '',
        age: '',
        height: '',
        remarks: '',
        face_img: [],
        phone: ''
      },
      ralationList: [],
      temp_img_path: [],
      pic_form_data: {},
      agree_list: [
        {
          checked: false,
          txt1: '我已阅读并同意',
          txt2: '《人人寻创建脸谱协议》'
        }
      ]
    }
  },
  // 加载 同时填充数据
  onLoad(op) {
		this.get_user_phone_list()
		this.human_id = op.id
    if (op.id) {
			uni.setNavigationBarTitle({
					title: '编辑脸谱'
			});
			;(async () => {
			  await this.get_family_relaionship()
			  this.get_edit_infomation(op.id)
			})()
    } else {
			uni.setNavigationBarTitle({
					title: '添加脸谱'
			});
			this.get_family_relaionship()
      
    }
  },
  onShow() {
    this.get_user_phone_list()
  },

  methods: {
    // 查看创建脸谱协议
    see_face_protocal() {
      uni.navigateTo({
        url: '../self/sub/face_protocal'
      })
    },
    // 获取编辑脸谱详细信息
    get_edit_infomation(id) {
      let self = this
      this.$u.api
        .get_the_detailof_facebook({
          id: id
        })
        .then((res) => {
          if (res.code == 200) {
            let data = res.data
            self.form.name = data.name
            self.form.age = data.age
            self.form.height = data.height

            for (var i = 0; i < self.ralationList.length; i++) {
              if (self.ralationList[i].name == data.label) {
                self.ralationList[i].checked = true
                self.form.relation = data.label
              }
            }

            // 性别 1男  2女
            data.sex == 1 ? (self.sex_box[0].checked = true) : (self.sex_box[1].checked = true)
            data.sex == 1 ? (this.form.sex = 1) : (this.form.sex = 2)

            let imgArr = data.face_img
            self.net_img = imgArr
            for (var i = 0; i < imgArr.length; i++) {
							if(self.local_img.indexOf('https') !== -1) {
								self.local_img.unshift(imgArr[i])
							} else {
								self.local_img.unshift(self.vuex_api_HEADER + imgArr[i])
							}
            }
						self.formPhone = res.data.phone;
						self.phone_list.forEach((phoVal) => {
						  phoVal.checked = false
						  res.data.phone.forEach((val) => {
						    if (phoVal.id === val.id) {
						      phoVal.checked = true
						    }
						  })
						})
          }
        })
    },
    // 用户删除图片
    user_delete_pic(index) {
      this.net_img.splice(index, 1)
      this.local_img.splice(index, 1)
    },

    // 上传照片
    chooseImg() {
      let that = this
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera'], //从相册选择
        success: function (res) {
          const imgSize = res.tempFiles[0] && res.tempFiles[0].size ? res.tempFiles[0].size : 0
          const imgName = res.tempFiles[0] && res.tempFiles[0].name ? res.tempFiles[0].name : ''
          that.photoCompress(res.tempFiles[0], (base64Codes) => {
            var fl = that.dataURLtoFile(base64Codes, imgName)
          })
          let local_path = res.tempFilePaths[0]
          ;(async () => {
            // 得到图片的方向
            let dir = 0
            if (that.vuex_sysinfo.indexOf('iOS') != -1) {
              dir = 0
            } else {
              let imginfo = await getImageData(local_path)
              dir = imginfo.exif.Orientation
            }
            let bs64 = await that.$u.utils.local_img2base64(local_path, dir)
            // 将bs64图片传送到服务器
            that.$u.api
              .upload_base64({
                chars: bs64,
                check: 1,
                camera: 0
              })
              .then(async (res) => {
                if (res.code != 200) {
                  that.$refs.uToast.show({
                    title: res.msg,
                    type: 'warning'
                  })
                } else {
                  if (dir != 1) {
                    let _path = await img_tool.base64ToPath(bs64)
                    that.local_img.unshift(_path)
                  } else {
                    that.local_img.unshift(local_path)
                  }
                  that.net_img.unshift(res.data.path)
                }
              })
          })()
        }
      })
    },
    photoCompress(file, objDiv) {
      // 压缩图片
      var ready = new FileReader()
      ready.readAsDataURL(file)
      const _this = this
      ready.onload = function () {
        var fileResult = this.result
        _this.canvasDataURL(fileResult, file.size, objDiv)
      }
    },
    canvasDataURL(path, size, callback) {
      var img = new Image()
      img.src = path
      var objCompressed = {}
      img.onload = function () {
        var that = this
        //默认压缩后图片规格
        var num = 15000 / size
        var quality = Math.round(num * 100) / 100
        var w = that.width
        var h = that.height
        var scale = w / h
        //实际要求
        w = objCompressed.width || w
        h = objCompressed.height || w / scale
        //生成canvas
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        // 创建属性节点
        var anw = document.createAttribute('width')
        anw.nodeValue = w
        var anh = document.createAttribute('height')
        anh.nodeValue = h
        canvas.setAttributeNode(anw)
        canvas.setAttributeNode(anh)
        ctx.drawImage(that, 0, 0, w, h)

        var base64 = canvas.toDataURL('image/jpeg', quality)
        // 回调函数返回base64的值
        callback(base64)
      }
    },
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    // 获取家庭关系
    get_family_relaionship() {
      this.$u.api
        .get_relation_list()
        .then((res) => {
          for (var i = 0; i < res.data.length; i++) {
            this.ralationList.push({
              name: res.data[i],
              checked: false
              // disabled: false
            })
          }
        })
        .catch((res) => {})
    },
    // 获取用户手机号
    get_user_phone_list() {
      this.$u.api
        .user_get_phone_list()
        .then((res) => {
          this.phone_list = []
          for (var i = 0; i < res.data.length; i++) {
            this.phone_list.push({
              id: res.data[i].id,
              mobile: res.data[i].mobile,
              checked: false
            })
          }
					if(this.human_id) {
						console.log('this.human_id', this.human_id)
						this.phone_list.forEach((phoVal) => {
						  phoVal.checked = false
						  this.formPhone.forEach((val) => {
						    if (phoVal.id === val.id) {
						      phoVal.checked = true
						    }
						  })
						})
					}
        })
        .catch((res) => {})
    },

    // 提交数据，生成脸谱
    generateFacebook() {
      let face_img = ''
      for (var i = 0; i < this.net_img.length; i++) {
        face_img = face_img + ',' + this.net_img[i]
      }
      face_img = face_img.slice(1)

      this.form.face_img = face_img
      let phone = ''
      for (var i = 0; i < this.phone_list.length; i++) {
        if (this.phone_list[i].checked == true) {
          phone = phone + ',' + this.phone_list[i].id
        }
      }
      if (false == this.must_check()) {
        return
      }
      this.form.phone = phone.slice(1)
			let submit_data = {};
			if(this.human_id) {
				submit_data = {
					id: this.human_id,
					name: this.form.name,
					label: this.form.relation, // 亲属关系
					sex: this.form.sex,
					age: this.form.age,
					height: this.form.height,
					face_img: face_img,
					phone: this.form.phone,
					remarks: 'not have'
				}
			} else {
			  submit_data = {
					name: this.form.name,
					label: this.form.relation, // 亲属关系
					sex: this.form.sex,
					age: this.form.age,
					height: this.form.height,
					face_img: face_img,
					phone: this.form.phone,
					remarks: 'not have'
				}
			}
      this.$u.api.user_creat_or_modify_facebook(submit_data).then((res) => {
        if (res.code == 200) {
          this.$refs.uToast.show({
            title: res.msg,
            type: 'success'
          })
          setTimeout(() => {
            uni.navigateBack({
							delta:1
						})
          }, 500)
        } else {
          this.$refs.uToast.show({
            title: res.msg,
            type: 'error'
          })
        }
      })
    },
    // 必填项检查
    must_check() {
      let hints = ['请补充姓名', '请确定家庭关系', '请选择性别', '请填写年龄', '请填写身高', '请上传包含人脸的照片', '请绑定你的联系方式', '同意协议后才能创建脸谱哦']
      let phone_sel = false
      for (var i = 0; i < this.phone_list.length; i++) {
        if (this.phone_list[i].checked == true) {
          phone_sel = true
          break
        }
      }
      let check_data = [
        this.form.name,
        this.form.relation, // 亲属关系
        this.form.sex,
        this.form.age,
        this.form.height,
        this.net_img.length == 0 ? '' : 'something',
        phone_sel == false ? '' : 'something',
        this.agree_list[0].checked == false ? '' : 'something'
      ]
      for (var i = 0; i < check_data.length; i++) {
        if (check_data[i] == '') {
          uni.showToast({
            title: hints[i],
            icon: 'none'
          })
          return false
        }
      }
      return true
    },
    // 性别确定
    sex_change(index) {
      this.form.sex = this.sex_box[index].value
    },
    // 关系确定
    relationChange(relation, index) {
      this.form.relation = relation
      for (var i = 0; i < this.ralationList.length; i++) {
        this.ralationList[i].checked = false //清空
      }
      this.ralationList[index].checked = true
    },
    // 添加其他手机号码
    goto_addmore_phonenumber() {
      uni.navigateTo({
        url: '../self/sub/phone_list'
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background: #f4f4f4;
}

#container {
  .banner {
    width: 750rpx;
    height: 100rpx;
  }

  .issue-btn {
    width: 572rpx;
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    background: linear-gradient(90deg, #69dee8, #52d2cf);
    border-radius: 45rpx;
    font-size: 18px;
    color: #ffffff;
    margin: 0 auto;
    position: relative;
    top: -42rpx;
  }

  .information {
    width: 698rpx;
    background: #ffffff;
    border-radius: 10rpx;
    margin: 0 auto;
    position: relative;
    top: -80rpx;

    .wx {
      width: 42rpx;
      height: 42rpx;
      padding-bottom: 24rpx;
    }

    .pic {
      position: relative;
      width: 146rpx;
      height: 146rpx;

      .img {
        width: 146rpx;
        height: 146rpx;
      }

      .txt {
        position: absolute;
        width: 106rpx;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        font-size: 13px;
        color: #fff;
      }
    }

    .phone-tips {
      color: red;
      padding: 30rpx 0 41rpx 0;
      padding-left: 53rpx;
      font-size: 18rpx;
    }

    .phone-add {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-wrap: wrap;
      padding: 0 0 73rpx 0;

      .phone-add-item {
        position: relative;
      }

      .close-icon {
        width: 32rpx;
        height: 32rpx;
        margin: 0 10rpx;
      }

      .phone-add-item,
      .phone-add-btn {
        width: 242rpx;
        height: 72rpx;
        border: 1rpx solid #cccccc;
        border-radius: 10rpx;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;

        .num {
        }

        .icon {
          width: 54rpx;
          height: 57rpx;
          position: absolute;
          bottom: 0;
          right: 0;
        }

        .plus {
          margin-right: 14rpx;
        }
      }
    }

    .img-content {
      padding-left: 53rpx;
      display: flex;
      flex-wrap: wrap;
      // align-items: flex-start;

      .title {
        color: red;
        padding: 30rpx 0 41rpx 0;
        font-size: 18rpx;
      }
    }

    .title {
      display: flex;
      align-items: center;
      padding: 31rpx 0 0 33rpx;

      .vertical-bar {
        width: 8rpx;
        height: 30rpx;
        background: #69dde8;
        border-radius: 4rpx;
        margin-right: 12rpx;
      }

      .txt {
        font-size: 16px;
        font-weight: 700;

        .tips {
          color: #ff0000;
          font-size: 18rpx;
          font-weight: normal;
        }
      }
    }

    .content {
      padding: 0 54rpx;

      .content-item {
        display: flex;
        width: 590rpx;
        margin: 0 auto;

        .u-form-item--left {
          height: 45rpx;
        }

        .u-form-item--right__content {
          display: flex;
        }

        .choose {
          padding-left: 38rpx;

          radio-group {
            display: flex;

            .uni-list-cell {
              display: flex;
              padding-right: 54rpx;
              margin-left: 50rpx;
            }
          }
        }

        .radio-label {
          // display: inline-block;
          padding: 0 20rpx;
          border: 1rpx solid rgb(228, 231, 237);
          // border-radius: 12rpx;
          margin: 0 10rpx 10rpx 0;
          background-color: #e8e8e8;
          color: #7b7b7b;

          .radio-box {
            vertical-align: top;
            right: 5rpx;
            top: -20rpx;
          }
        }

        .content-input {
          display: flex;
          align-items: center;
          width: 405rpx;
          height: 58rpx;
          border: 1rpx solid #cdcdcd;
          border-radius: 24rpx;
          padding-left: 20rpx;
          margin-left: 80rpx;
        }
      }
    }
  }
  .protocal {
    margin-top: 10rpx;
    background-color: transparent;
    text-align: center;
  }
}
</style>
